//
//  COOtherInfoController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/8.
//

import UIKit

class COOtherInfoController: COBaseController {
    
    var userId:String!

    lazy var pageNum: Int = 1
    var profileModel = DGChatUserInfoModel()
    fileprivate var photoArr  = [ProfilePhotosModel]()
    var favorableRes:String = ""
    var headHeight:CGFloat = 0.0
    
    // DispatchGroup-notify(不阻塞)
    let queueGroup = DispatchGroup()
    let queueQueue = DispatchQueue(label: "other_queue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil) // 创建并行队列
    
    let headIdentifier:String = "headView"
    var vHeadView = COStreamerReusableView()

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let width = (SCREENWIDTH - PTW(20))/3;
        layout.itemSize = CGSize(width: width, height: PTW(185))
        layout.sectionInset = UIEdgeInsets(top: PTW(5), left: PTW(5), bottom: PTW(160) + KSafeBottomMargin , right: PTW(5))
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = PTW(2)
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.backgroundColor = .clear
        view.dataSource = self
        view.delegate = self
        view.bounces = true
        view.alwaysBounceVertical = true
        view.showsVerticalScrollIndicator = false
        view.register(COStreamerCollectionCell.self, forCellWithReuseIdentifier: "COStreamerCollectionCell")
        view.register(COStreamerReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headIdentifier)
        return view
    }()
    
    // 视频
    lazy var videoBtn: UIButton = {
        let video = UIButton()
        video.addTarget(self, action: #selector(videoAction), for: .touchUpInside)
        return video
    }()
    
    // 关注
    lazy var followBtn: UIButton = {
        let video = UIButton()
        video.setImage(KImaged("coco_profile_likeNormal"), for: .normal)
        video.setImage(KImaged("coco_profile_likeSelect"), for: .selected)
        video.addTarget(self, action: #selector(followAction), for: .touchUpInside)
        return video
    }()
    
    // 消息
    lazy var msgBtn: UIButton = {
        let msg = UIButton()
        msg.setImage(KImaged("coco_profile_msg"), for: .normal)
        msg.addTarget(self, action: #selector(msgAction), for: .touchUpInside)
        return msg
    }()
    
    lazy var priceLbl: UILabel = {
        let name = UILabel()
        name.textColor = UIColor.white
        name.font = UIFont.pingfangFont(ofSize: PTW(15), weight: .medium)
        name.backgroundColor = UIColor.colorWithHex("#7863A6", 0.3)
        name.layer.cornerRadius = PTW(13)
        name.layer.masksToBounds = true
        name.textAlignment = .center
        return name
    }()
    
    lazy var moreBtn :UIButton = {
        let back = UIButton()
        back.setImage(KImaged("coco_profile_more"), for: .normal)
        back.addTarget(self, action: #selector(showTip), for: .touchUpInside)
        return back
    }()
    
    lazy var tagsArr: NSMutableArray = {
        let arr = NSMutableArray()
        return arr
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        kLiveCalling.keySaveToNSDefaults(with: false)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addnav()
        navView.addSubview(self.moreBtn)
        moreBtn.snp.makeConstraints { make in
            make.size.centerY.equalTo(fanhuiBtn)
            make.right.equalToSuperview().offset(-PTW(10))
        }
        self.view.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(KStatusAndNavBarHeight)
        }
        self.collectionView.footerRefresh {[weak self] in
            self?.pageNum += 1
            self?.loadProfileInfo(isRefresh:false)
        }
        self.collectionView.mj_footer?.isHidden = true
        // 加载数据
        loadProfileInfo(isRefresh:true)
        self.vHeadView.isHidden = true
    }
    
    func loadProfileInfo(isRefresh:Bool){
        if (isRefresh) {
            self.pageNum = 1;
        }
        UIToolHelper.showHUD()
        if (isRefresh){
            queueGroup.enter()
            queueQueue.async { [weak self] in
                guard let `self` = self else { return }
                var params = [String:Any]()
                params["streamerId"]  = self.userId
                COHttpManager.request(target: COBaseApi.streamerInfo(param: params), modelType: COChatStreamerInfoModel.self) { code, object, success in
                    let model = object?.steamer
                    self.profileModel = model ?? DGChatUserInfoModel()
                    self.queueGroup.leave()
                } failureBlock: { code, msg in
                    self.queueGroup.leave()
                }
                // 好评率
                queueGroup.enter()
                queueQueue.async { [weak self] in
                    guard let `self` = self else { return }
                    var params = [String:Any]()
                    params["streamerId"]  = self.userId
                    COHttpManager.request(target: COBaseApi.favorableParse(param: params), modelType: COProfileFavorableModel.self) { code, object, success in
                        self.favorableRes = object?.res ?? "0"
                        self.queueGroup.leave()
                    } failureBlock: { code, msg in
                        self.queueGroup.leave()
                    }
                }
            }
        }
        queueGroup.enter()
        queueQueue.async { [weak self] in
            guard let `self` = self else { return }
            var params = [String:Any]()
            params["streamerId"]  = self.userId
            params["pageNum"]  = self.pageNum
            params["pageSize"]  = 20
            COHttpManager.request(target: COBaseApi.sreamerPhoto(param: params), modelType: COProfileInfoListModel.self) {[weak self] code, object, success in
                let list = object?.pageData
                if isRefresh == true {
                    self?.photoArr = list ?? [ProfilePhotosModel]()
                    self?.collectionView.footerEndRefreshing((list?.count == 0) ? true : false)
                }else {
                    if list?.count ?? 0 > 0 {
                        if let items = self?.photoArr, let list = list{
                            self?.photoArr = items + list
                        }
                    }
                    self?.collectionView.footerEndRefreshing((list?.count == 0) ? true : false)
                }
                self?.queueGroup.leave()
            } failureBlock: {[weak self] code, msg in
                self?.collectionView.footerEndRefreshing()
                self?.queueGroup.leave()
            }
        }
        queueGroup.notify(queue: queueQueue) {
            DispatchQueue.main.async {
                UIToolHelper.hideHUD()
                self.setUpUI()
            }
        }
    }
    
    // UI布局
    func setUpUI(){
        self.vHeadView.isHidden = false
        self.tagsArr.removeAllObjects()
        for i in 0..<self.profileModel.tagsResponses.count {
            let tagmodel = self.profileModel.tagsResponses[i]
            let tagStr = "\(tagmodel.tagsName)(\(tagmodel.hits))"
            self.tagsArr.add(tagStr)
        }
        let tagViewHeight = DGTezTagView.getTotalHeightWithValuesAndWords(words: self.tagsArr as! [String], sMargin: PTW(50), HMargin: PTW(25), IMargin: PTW(5))
        self.headHeight = PTW(320) + tagViewHeight
        self.profileModel.tagArrs = self.tagsArr as! [String]
        self.profileModel.resCount = self.favorableRes
        self.collectionView.reloadData()
        
        view.addSubview(self.videoBtn)
        view.addSubview(self.msgBtn)
        view.addSubview(self.followBtn)
        view.addSubview(self.priceLbl)
        videoBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(PTW(195), PTW(80)))
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-PTW(30)-KSafeBottomMargin)
        }
        msgBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(PTW(80), PTW(80)))
            make.centerY.equalTo(self.videoBtn)
            make.right.equalTo(self.videoBtn.snp.left).offset(PTW(5))
        }
        followBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(PTW(80), PTW(80)))
            make.centerY.equalTo(self.videoBtn)
            make.left.equalTo(self.videoBtn.snp.right).offset(-PTW(5))
        }
        priceLbl.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(PTW(88), PTW(26)))
            make.centerX.equalToSuperview()
            make.centerY.equalTo(videoBtn.snp.bottom)
        }
        //是否在线，1在线、2繁忙2繁忙,3下线
        if (self.profileModel.status == 1){
            self.videoBtn.setImage(KImaged("coco_profile_online"), for: .normal)
        }else if (self.profileModel.status == 2){
            self.videoBtn.setImage(KImaged("coco_profile_busy"), for: .normal)
        }else{
            self.videoBtn.setImage(KImaged("coco_profile_offline"), for: .normal)
        }
        
        self.priceLbl.attributedText = "\(self.profileModel.price)/min".stringWithImage(img: "coco_mine_star", bounds: CGRect(x: 0, y: -PTW(2) , width: PTW(12) , height: PTW(12)),isFirst: true)
        self.followBtn.isSelected = self.profileModel.isFollow ?? 0 > 0
        
    }
    
    //MARK: ------------- 视频点击 ------------------
    @objc func videoAction(){
        self.requestStatus(userId: self.userId, rechargeType: 2)
    }
    
    //MARK: ------------- 关注点击 ------------------
    @objc func followAction(sender:UIButton){
        var params = [String:Any]()
        params["streamerId"]  = self.profileModel.id
        UIToolHelper.showHUD()
        if (self.profileModel.isFollow ?? 0 > 0){
            // 取消关注
            COHttpManager.request(target: COBaseApi.streamerUnFollow(param: params), modelType: CONSObjectModel.self) {[weak self] code, object, success in
                UIToolHelper.hideHUD()
                self?.profileModel.isFollow = 0
                sender.isSelected = false
                self?.profileModel.fans -= 1
                self?.vHeadView.setFans(fansNum: self?.profileModel.fans ?? 0)
                UIToolHelper.makeToast("Sussessful!")
                NotificationCenter.default.post(name: .FollowFinishNoti, object: nil)
            } failureBlock: { code, msg in
                UIToolHelper.hideHUD()
                UIToolHelper.makeToast("Network error,Please try again later!")
            }
        }else{
            // 关注
            COHttpManager.request(target: COBaseApi.streamerFollow(param: params), modelType: CONSObjectModel.self) {[weak self] code, object, success in
                UIToolHelper.hideHUD()
                self?.profileModel.isFollow = 1
                sender.isSelected = true
                self?.profileModel.fans += 1
                self?.vHeadView.setFans(fansNum: self?.profileModel.fans ?? 0)
                UIToolHelper.makeToast("Sussessful!")
                NotificationCenter.default.post(name: .FollowFinishNoti, object: nil)
            } failureBlock: { code, msg in
                UIToolHelper.hideHUD()
                UIToolHelper.makeToast("Network error,Please try again later!")
            }
        }
    }
    
    //MARK: ------------- 消息点击 ------------------
    @objc func msgAction(){
        let chat = COChatViewController()
        chat.conversationType = .ConversationType_PRIVATE
        chat.targetId = "streamer_\(self.userId!)"
        self.navigationController?.pushViewController(chat, animated: true)
        RCIMClient.shared().clearMessagesUnreadStatus(.ConversationType_PRIVATE, targetId: chat.targetId)
        COChatMsgManager.shared.setBadgeValue()
    }
}

extension COOtherInfoController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photoArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "COStreamerCollectionCell", for: indexPath) as! COStreamerCollectionCell
        cell.photoModel = self.photoArr[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        let cell = collectionView.cellForItem(at: indexPath) as! COStreamerCollectionCell
        let photoView = MOPhotoPreviewer()
        photoView.preview(fromImageView: cell.iconView, container: self.view)
    }
    
    //设置HeadView的宽高
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
        return CGSize(width: SCREENWIDTH, height: self.headHeight)
    }

    //返回自定义HeadView
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader{
            vHeadView = collectionView.dequeueReusableSupplementaryView(ofKind:kind, withReuseIdentifier: headIdentifier, for: indexPath) as! COStreamerReusableView
            vHeadView.headModel = self.profileModel
        }
        return vHeadView
    }
}
